package cn.itsource.pet.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.itsource.basic.exception.BusinessException;
import cn.itsource.basic.service.impl.BaseServiceImpl;
import cn.itsource.basic.utils.*;
import cn.itsource.order.domain.OrderPetAcquisition;
import cn.itsource.order.mapper.OrderPetAcquisitionMapper;
import cn.itsource.org.domain.Employee;
import cn.itsource.org.domain.Shop;
import cn.itsource.org.mapper.EmployeeMapper;
import cn.itsource.org.mapper.ShopMapper;
import cn.itsource.pet.domain.SearchMasterMsg;
import cn.itsource.pet.domain.SearchMasterMsgAuditLog;
import cn.itsource.pet.mapper.SearchMasterMsgAuditLogMapper;
import cn.itsource.pet.mapper.SearchMasterMsgMapper;
import cn.itsource.pet.query.SearchMasterMsgQuery;
import cn.itsource.pet.service.ISearchMasterMsgService;
import cn.itsource.user.domain.Logininfo;
import cn.itsource.user.domain.User;
import cn.itsource.user.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map;

/**
 * 业务实现类：
 */
@Service
public class SearchMasterMsgServiceImpl extends BaseServiceImpl<SearchMasterMsg> implements ISearchMasterMsgService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;
    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private OrderPetAcquisitionMapper orderPetAcquisitionMapper;

    @Autowired
    private SearchMasterMsgAuditLogMapper searchMasterMsgAuditLogMapper;

    @Transactional
    @Override
    public AjaxResult publish(SearchMasterMsg searchMasterMsg, HttpServletRequest request) {
        //校验空值
        String title = searchMasterMsg.getTitle();
        String name = searchMasterMsg.getName();
        String address = searchMasterMsg.getAddress();
        if (StrUtil.isBlank(title) || StrUtil.isBlank(name) || StrUtil.isBlank(address)) {
            throw new BusinessException("信息不能为空");
        }
        //百度Ai智能审核
        //百度AI智能审核：校验文本-标题+昵称
        Boolean boo1 = BaiduAiUtils.textCensor(title + name);
        //百度AI智能审核：校验图片-resources，多张图片
        Boolean boo2 = BaiduAiUtils.imgCensors(searchMasterMsg.getResources());


        //二：添加数据库，state=0，审核日志是在人工审核的时候【要获取当前登录人】
        if (boo1 && boo2) {
            searchMasterMsg.setState(0);//待审核
            Logininfo logininfo = LoginContextUtils.getLogininfo(request);
            User user = userMapper.findByLogininfoId(logininfo.getId());
            //哪一个用户发布的寻主消息
            searchMasterMsg.setUserId(user.getId());
            searchMasterMsgMapper.add(searchMasterMsg);
        } else {
            throw new BusinessException("标题或者昵称,图片不合法");
        }
        return new AjaxResult();
    }

    @Override
    public PageResult<SearchMasterMsg> finish(SearchMasterMsgQuery query, HttpServletRequest request) {
        query.setState(2); //已完成寻主消息
        Logininfo logininfo = LoginContextUtils.getLogininfo(request);
        Employee employee = employeeMapper.findByLogininfoId(logininfo.getId());
        if(employee.getShopId() != null){
            query.setShopId(employee.getShopId());
        }
        return super.queryPage(query);
    }

    @Override
    public PageResult<SearchMasterMsg> toAudit(SearchMasterMsgQuery query, HttpServletRequest request) {
        query.setState(0);//待审核
        Logininfo logininfo = LoginContextUtils.getLogininfo(request);
        Employee employee = employeeMapper.findByLogininfoId(logininfo.getId());
        if(employee.getShopId() != null){//店铺管理员
          throw new BusinessException("恁没有权限");
        }
        return super.queryPage(query);
    }

    @Override
    public PageResult<SearchMasterMsg> toPool(SearchMasterMsgQuery query, HttpServletRequest request) {
        query.setState(3);//寻主池
        return super.queryPage(query);
    }

    @Override
    public PageResult<SearchMasterMsg> toHandle(SearchMasterMsgQuery query, HttpServletRequest request) {
        query.setState(1);//已完成
        Logininfo logininfo = LoginContextUtils.getLogininfo(request);
        Employee employee = employeeMapper.findByLogininfoId(logininfo.getId());
        if(employee.getShopId() != null){//店铺管理员
            query.setShopId(employee.getShopId());
        }
        return super.queryPage(query);
    }


    //寻主消息-人工审核
    @Override
    public AjaxResult audit(SearchMasterMsgAuditLog log, HttpServletRequest request) {
        //审核成功：1.分配最近的店铺 2.更新消息状态为1或3【1-找到店铺，3-寻主池】 3.告诉店铺管理员-接单 4.添加审核日志
        //审核失败：1.更新消息状态为-1 2.告诉用户审核失败-重新填写 3.添加审核日志
        SearchMasterMsg msg = searchMasterMsgMapper.findOne(log.getMsgId());
        if(log.getState() == 1){//审核通过
            //1.分配最近的店铺
            Point point = DistanceUtils.getPoint(msg.getAddress());//寻主消息发布时的地址=用户地址=宠物现在的地址
            Shop shop = DistanceUtils.getNearestShop(point, shopMapper.findAll());
            if(shop == null){//放入寻注池
                msg.setState(3);//2.更新消息状态
            }else{//找到了最近的店铺
                msg.setShopId(shop.getId());
                msg.setState(1);//2.更新消息状态 - 审核通过待处理
                //3.找到了店铺 - 告诉店铺管理员-接单【真实场景-发短信】
                System.out.println("你有新的订单，请及时处理");
            }
        }else{//审核不通过
            msg.setState(-1);//1.更新消息状态为-1
            //2.告诉用户审核失败-重新填写【真实场景-发短信】
            System.out.println("非常抱歉，你发布的寻主消息未能审核通过，请重新填写");
        }
        //添加审核日志
        Logininfo logininfo = LoginContextUtils.getLogininfo(request);
        Employee employee = employeeMapper.findByLogininfoId(logininfo.getId());
        log.setAuditId(employee.getId());
        searchMasterMsgAuditLogMapper.add(log);
        //更新寻主消息状态
        searchMasterMsgMapper.update(msg);
        return new AjaxResult();
    }


    @Override
    public AjaxResult reject(Long msgId) {
        //拒单：消息已经分配给店铺了，店铺由于某些原因拒绝接单-拒绝接单之后寻主消息放回寻主池中
        searchMasterMsgMapper.reject(msgId);
        return new AjaxResult();
    }

    @Override
    public AjaxResult accept(Map<String,String> map) {
        Long msgId = Long.valueOf(map.get("msgId"));
        OrderPetAcquisition orderPetAcquisition = orderPetAcquisitionMapper.findByMsgId(msgId);
        if (orderPetAcquisition != null){
            throw new BusinessException("订单正在处理，请勿重复接单...");
        }
        SearchMasterMsg msg = searchMasterMsgMapper.findOne(msgId);
        OrderPetAcquisition order = map2One(msg,map);
        orderPetAcquisitionMapper.add(order);
        return new AjaxResult();
    }

    private OrderPetAcquisition map2One(SearchMasterMsg msg, Map<String,String> map) {
        OrderPetAcquisition order = new OrderPetAcquisition();
        String orderSn = CodeGenerateUtils.generateOrderSn(msg.getUserId());//生成订单编号
        order.setOrderSn(orderSn);
        order.setDigest(map.get("note"));
        //最后确认时间
        order.setLastcomfirmtime(new Date(System.currentTimeMillis()+3*24*60*60*1000));
        order.setState(0);//待处理
        order.setPrice(msg.getPrice());
        //order.setPaytype();//支付类型
        //order.setPetId();//宠物id
        order.setUserId(msg.getUserId());
        order.setShopId(msg.getShopId());
        order.setAddress(msg.getAddress());
        order.setEmpId(Long.valueOf(map.get("handler")));
        order.setSearchMasterMsgId(msg.getId());
        return order;
    }

}
